<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属科室" prop="deptId">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择科室"
          clearable
          @change="handleQuery"
        >
          <el-option
            label="全部科室"
            :value="null"
          />
          <el-option
            v-for="item in deptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医生姓名" prop="doctName">
        <el-input
          v-model="queryParams.doctName"
          placeholder="请输入医生"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排班日期" prop="schedDate">
        <el-date-picker clearable
          v-model="queryParams.schedDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择排班日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"

        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"

        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"

        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"

        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newscheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="科室" align="center" prop="deptId">
        <template slot-scope="scope">
          {{
            (deptOptions.find(item => item.deptId === scope.row.deptId) &&
            deptOptions.find(item => item.deptId === scope.row.deptId).deptName)
            || '未知科室'
          }}
        </template>
      </el-table-column>
      <el-table-column label="医生姓名" align="center" prop="doctName" />
      <el-table-column label="排班日期" align="center" prop="schedDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.schedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改newschedule对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属科室">
              <el-select v-model="form.deptId" placeholder="请选择科室" clearable @change="handleDeptChange">
                <el-option
                  v-for="item in deptOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
        <el-form-item label="医生姓名" prop="doctId">
          <el-select v-model="form.doctId" placeholder="请选择医生" clearable @change="handleDoctorChange">
            <el-option
              v-for="doctor in doctorList"
              :key="doctor.doctId"
              :label="doctor.doctName"
              :value="doctor.doctId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医生姓名" prop="doctName"v-if="false">
          <el-input v-model="form.doctName" placeholder="医生姓名" readonly />
        </el-form-item>
        <el-form-item label="排班日期" prop="schedDate">
          <el-date-picker clearable
            v-model="form.schedDate"
            type="dates"
            value-format="yyyy-MM-dd"
            placeholder="请选择排班日期">
          </el-date-picker>
          <div class="selected-dates">
            <el-tag
              v-for="(date, index) in form.schedDate"
              :key="index"
              closable
              @close="removeDate(index)"
            >
              {{ date }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNewschedule, getNewschedule, delNewschedule, addNewschedule, updateNewschedule } from "@/api/his/newschedule";
import { getDocListByDepy,getDoctor} from "@/api/his/doctor";
import { listDept} from "@/api/his/dept";

export default {
  name: "Newschedule",
  dicts: ['his_department'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // newschedule表格数据
      newscheduleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        doctId: null,
        schedDate: null,
        timePeriod: null,
      },
      // 表单参数
      form: {},
      // 医生列表
      doctorList: [],
       // 科室选项
       deptOptions: [],
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "科室ID不能为空", trigger: "change" }
        ],
        doctId: [
          { required: true, message: "医生ID不能为空", trigger: "blur" }
        ],
        schedDate: [
          { required: true, message: "排班日期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    listDept().then(response => {
        this.deptOptions = response.rows;
      });
  },
  methods: {
    removeDate(index) {
    this.form.schedDates.splice(index, 1)
  },
    /** 查询newschedule列表 */
    getList() {
      this.loading = true;
      listNewschedule(this.queryParams).then(response => {
        this.newscheduleList = response.rows;
        this.total = response.total;
        this.loading = false;

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        schedId: null,
        deptId: null,
        doctId: null,
        schedDate: null,
        timePeriod: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.schedId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增排班";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const schedId = row.schedId || this.ids
      getNewschedule(schedId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改newschedule";
        this.getDoctorListByDeptId(this.form.deptId);
    // 设置医生姓名
    this.$nextTick(() => {
      this.handleDoctorChange(this.form.doctId);
    });
      });
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.schedId != null) {
    //         updateNewschedule(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addNewschedule(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    submitForm() {
    this.$refs.form.validate(valid => {
      if (valid) {
        // 创建请求数组
        const requests = this.form.schedDate.map(date => {
          return addNewschedule({
            deptId: this.form.deptId,
            doctId: this.form.doctId,
            doctName: this.form.doctName,
            schedDate: date,
          })
        })

        // 批量提交
        Promise.all(requests)
          .then(() => {
            this.$modal.msgSuccess("排班创建成功")
            this.open = false
            this.getList()
          })
      }
    })
  },
    /** 删除按钮操作 */
    handleDelete(row) {
      const schedIds = row.schedId || this.ids;
      this.$modal.confirm('是否确认删除').then(function() {
        return delNewschedule(schedIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('his/newschedule/export', {
        ...this.queryParams
      }, `newschedule_${new Date().getTime()}.xlsx`)
    },
    /** 根据科室ID获取医生列表 */
    getDoctorListByDeptId(deptId) {
      getDocListByDepy(deptId).then(response => {
      this.doctorList = response.data;
    });
    },
    /** 科室选择变化时触发 */
  handleDeptChange(deptId) {
    this.getDoctorListByDeptId(deptId);
  },
  handleDoctorChange(doctId) {
  const selectedDoctor = this.doctorList.find(doctor => doctor.doctId === doctId);
  if (selectedDoctor) {
    this.form.doctName = selectedDoctor.doctName;
  } else {
    this.form.doctName = '';
  }
},


  }
};
</script>
